const path = require('path');

const typeParse = (target, dftVal) => target ? JSON.parse(target) : dftVal;

const resolve = (dir) => path.join(__dirname, dir);

const isDevEnv = process.env.NODE_ENV === 'development';

const devNeedCDN = typeParse(process.env.VUE_APP_DEV_NEED_CDN, false);

const isEnableProxy = typeParse(process.env.VUE_APP_ENABLE_PROXY);

const cdn = {
   css: [],
   js: [
      'https://cdn.staticfile.org/vue/2.6.11/vue.min.js',
      'https://cdn.staticfile.org/vuex/3.0.1/vuex.min.js',
      'https://cdn.staticfile.org/vue-router/3.0.1/vue-router.min.js',
      'https://cdn.staticfile.org/axios/0.19.0/axios.min.js',
      'https://cdn.staticfile.org/jquery/2.2.3/jquery.min.js'
   ],
   externals: {
      'vue': 'Vue',
      'vuex': 'Vuex',
      'vue-router': 'VueRouter',
      'axios': 'axios',
      'jquery': '$'
   }
};

const config = {
    publicPath: '/',
    outputDir: 'dist', //这是默认值
    assetsDir: 'static', //这是默认值
    //开发环境，启用eslint校验
    lintOnSave: false,
    //生成环境关闭source-map文件              
    productionSourceMap: isDevEnv,
    configureWebpack: {
        name: '钢贸云 科学运营，驱动未来',
        devtool: isDevEnv ? 'source-map' : 'none',
        resolve: {
            extensions: ['.js', '.vue', '.jsx', '.json']
        }
    },
    // css相关配置
    css: {
        extract: !isDevEnv, // 是否使用css分离插件 ExtractTextPlugin
        sourceMap: isDevEnv // 开启 CSS source maps
    },
    chainWebpack(config) {

        config.plugins.delete('prefetch');

        config.plugin('preload').tap(() => [
            {
                rel: 'preload',
                // to ignore runtime.js
                fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
                include: 'initial'
            }
        ]);
        
        config.module
            .rule('images')
            .test(/\.(png|jpe?g|gif|webp)(\?.*)?$/)
            .use('image-webpack-loader')
            .loader('image-webpack-loader')
            .options({ bypassOnDebug: true })
            .end()

        //生成环境或开发环境需要使用cdn时    
        config.when(!isDevEnv || devNeedCDN, config => {
            config.externals(cdn.externals);
            config
                .plugin('html')
                .tap(args => {
                    args[0].cdn = cdn;
                    return args;
                });
        });
        
        // 代码分割，并发请求速度更快
        config.optimization.runtimeChunk('single'); //运行时文件单独打包
        config.optimization.splitChunks({
            chunks: "all",
            maxInitialRequests: Infinity,
            minSize: 300000, // 依赖包超过30kb将被单独打包
            automaticNameDelimiter: "-",
            cacheGroups: {
                // 第三方模块分割
                vendor: {
                    test: /[\\/]node_modules[\\/]/,
                    name(module) {
                        const packageName = module.context.match(
                            /[\\/]node_modules[\\/](.*?)([\\/]|$)/
                        )[1];
                        return `chunk.${packageName.replace("@", "")}`;
                    },
                    priority: 10, //值越大，越优先分割。分割的优先级越高
                },
                // 对指定第三方模块，再次分割
                chinaTownJson: {
                    name: 'chunk-chinaTownJson',
                    test: /[\\/]node_modules[\\/]_?province-city-china(.*?)[\\/]dist[\\/]town.json$/,
                    priority: 20
                },
                chinaCityJson: {
                    name: 'chunk-chinaCityJson',
                    test: /[\\/]node_modules[\\/]_?province-city-china(.*?)[\\/]dist[\\/]data.json$/,
                    priority: 30
                },
                // 公共模块分割
                common: {
                    chunks: 'initial',
                    name:'common',
                    priority: 0,
                    minSize: 0, 
                    minChunks: 2,
                    reuseExistingChunk: true // 如果本来已经把代码提取出来，则重用存在的而不是重新产生
                }
            }
        });

        config
            .resolve
            .alias
            .set('@', resolve('src'))
            .end()
            .symlinks(true);    //修复HMR

        // set svg-sprite-loader
        config.module
            .rule('svg')
            .exclude.add(resolve('src/icons'))
            .end();
        config.module
            .rule('icons')
            .test(/\.svg$/)
            .include
            .add(resolve('src/icons'))
            .end()
            .use('svg-sprite-loader')
            .loader('svg-sprite-loader')
            .options({
                symbolId: 'icon-[name]'
            })
            .end();    

        //分析环境下，使用分析工具
        config.when(process.env.ANALYZ == 'analyz', config => {
            config
                .plugin('webpackBundleAnalyzer')
                .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin);
        });
    },

};

//配置代理
if(!!isEnableProxy && isDevEnv){
    //webpack-dev-server
    // const proxyPath = process.env.VUE_APP_PROXY_PATH;
    // const resourcePath = process.env.VUE_APP_PROXY_RESOURCE_PATH;
    // config.devServer = {
    //     contentBase: './dist',
    //     //开启热更新，必要要配置热更新插件才有效果
    //     inline: true,
    //     host: process.env.VUE_APP_HOST,
    //     port: typeParse(process.env.VUE_APP_PORT, '1803'),
    //     //构建结束后，自动打开浏览器
    //     open: true,
    //     //启用Gzip压缩
    //     compress: true,
    //     https: false,
    //     hotOnly: false,
    //     disableHostCheck: true,
    //     proxy: {
    //         [proxyPath]: {
    //             target: process.env.VUE_APP_PROXY_HOST,
    //             changeOrigin: true,
    //             ws: false,
    //             pathRewrite: {
    //                 [proxyPath]: ''
    //             }
    //         },
    //         [resourcePath]: {
    //             target: process.env.VUE_APP_RESOURCE_HOST,
    //             changeOrigin: true,
    //             ws: false,
    //             pathRewrite: {
    //                 [resourcePath]: ''
    //             }
    //         }
    //     }
    // };
}

module.exports = config;
